<?php

namespace app\shop\controller\Product;

use think\Controller;

class Product extends Controller
{
    // 商品模型
    protected $ProductModel = null;

    // 订单模型
    protected $OrderModel = null;

    // 订单商品模型
    protected $OrderProductModel = null;

    // 购物车模型
    protected $CartModel = null;
    protected $BusinessModel = null;
    protected $RecordModel = null;

    // 初始化操作
    public function _initialize()
    {
        $this->ProductModel = model('Product.Product');

        $this->OrderModel = model('Order.Order');
        $this->OrderProductModel = model('Order.Product');
        $this->BusinessModel = model('Business.Business');
        $this->RecordModel = model('Business.Record');
        $this->CartModel = model('Order.Cart');
    }

    public function index()
    {
        $typeid = $this->request->param('typeid', 0, 'trim');
        $orderBy = $this->request->param('order', 'createtime', 'trim');
        $flag = $this->request->param('flag', 0, 'trim');

        $name = $this->request->param('proName', 0, 'trim');

        $where = [];

        if ($typeid) {
            $where['typeid'] = $typeid;
        }

        if ($flag) {
            $where['flag'] = $flag;
        }

        if ($name) {

            $ProductData = $this->ProductModel->where('name', 'like',  '%' . $name . '%')->order("$orderBy DESC")->select();

            $this->success('查询成功', null, $ProductData);

            return false;
        }

        $where['status'] = 1;

        $ProductData = $this->ProductModel->where($where)->order("$orderBy DESC")->select();

        $this->success('查询成功', null, $ProductData);
    }

    public function info()
    {
        $proid = $this->request->param('proid', 0, 'trim');

        $busid = $this->request->param('busid', 0, 'trim');

        $ProductInfo = $this->ProductModel->find($proid);

        if (!$ProductInfo) {
            $this->error('商品不存在');
        }

        $collection = model('Business.Collection')->where(['busid' => $busid, 'proid' => $proid])->find();

        $ProductInfo['CollStatus'] = false;

        if ($collection) {
            $ProductInfo['CollStatus'] = true;
        }

        $this->success('查询成功', null, $ProductInfo);
    }

    // 同时做收藏以及取消收藏
    public function collection()
    {
        $busid = $this->request->param('busid', 0, 'trim');

        $proid = $this->request->param('proid', 0, 'trim');

        $Product = $this->ProductModel->find($proid);

        if (!$Product) {
            $this->error('商品不存在');
        }

        $Business = model('Business.Business')->find($busid);

        if (!$Business) {
            $this->error('非法登录', null, ['action' => 'login']);
        }

        // 组装条件
        $where = [
            'proid' => $proid,
            'busid' => $busid
        ];

        $collection = model('Business.Collection')->where($where)->find();

        // 提示信息
        $msg = '';

        $result = null;

        $status = false;

        if ($collection) {
            // 在收藏表能找到数据，说明已经收藏过 => 取消收藏
            $result = $collection->delete();

            $msg = '取消收藏';
        } else {
            // 说明没有收藏过 => 收藏
            $data = [
                'proid' => $proid,
                'busid' => $busid,
            ];

            $result = model('Business.Collection')->validate('common/Business/Collection')->save($data);

            $msg = '收藏';

            $status = true;
        }

        if ($result === FALSE) {
            $this->error($msg . '失败');
        } else {
            $this->success($msg . '成功', null, ['status' => $status]);
        }
    }

    public function buyNow()
    {
        // 如果前台从商品详情页面进入，就获取到传入的商品id
        $proid = $this->request->param('proid', '', 'trim');

        $cartid = $this->request->param('cartids', '', 'trim');

        $total = $this->request->param('total', 0, 'trim');

        $addrid = $this->request->param('addrid', 0, 'trim');

        $busid = $this->request->param('busid', 0, 'trim');

        $content = $this->request->param('content', '', 'trim');

        $CartList = $this->CartModel->with(['product'])->whereIn('cart.id', $cartid)->select();


        $product = $this->ProductModel->where('id', $proid)->find();
        // halt($this->ProductModel->getLastSql());


        if (!$product) {
            $this->error('商品不存在');
        }

        $Business = $this->BusinessModel->find($busid);

        if (!$Business) {
            $this->error('用户不存在');
        }

        $Address = model('Business.Address')->find($addrid);

        if (!$Address) {
            $this->error('收货地址不存在');
        }



        // 判断用户余额是否足够下单
        if ($Business['money'] < $total) {
            $this->error('余额不足');
        }

        /* 
            order => 新增订单
            order_product => 新增订单关联商品数据

            product => 需要更新商品库存
            business => 更新用户的余额
            business_record => 新增该用户消费记录

            order_cart => 下单成功后需要把已下单的购物车商品删除

            事务操作
        */

        // 开启事务
        $this->OrderModel->startTrans();
        $this->OrderProductModel->startTrans();
        $this->ProductModel->startTrans();
        $this->BusinessModel->startTrans();
        $this->RecordModel->startTrans();
        $this->CartModel->startTrans();

        // 封装订单数据
        $OrderData = [
            'code' => build_code('BU'),
            'busid' => $busid,
            'businessaddrid' => $addrid,
            'amount' => $total,
            'remark' => $content,
            'status' => 2
        ];
        // halt($OrderData);

        // 插入数据库
        $OrderStatus = $this->OrderModel->validate('common/Order/Order')->save($OrderData);

        if ($OrderStatus === FALSE) {
            $this->error($this->OrderModel->getError());
        }


        // 封装订单商品数据
        $OrderProductData = [
            'orderid' => $this->OrderModel->id,
            'proid' => $proid,
            'pronum' => 1,
            'price' => $total,
            'total' => $total
        ];
        // halt($OrderProductData);

        // 实例化验证器

        // halt($OrderProductData);
        // 批量插入数据库
        $OrderProductStatus = $this->OrderProductModel->save($OrderProductData);
        // halt($this->OrderProductModel->getLastSql());

        if ($OrderProductStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->error('新增订单商品记录失败');
        }

        // $stock = $product['stock'];
        // halt($stock - 1);


        // 封装商品数据
        $ProductData = [
            'id' => $proid,
            'stock' => bcsub($product['stock'], 1)
        ];


        $ProductStatus = $this->ProductModel->isUpdate(true)->saveAll($ProductData);

        if ($ProductStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->error('更新库存失败');
        }


        // 封装用户的余额
        $BusinessData = [
            'id' => $busid,
            'money' => bcsub($Business['money'], $total, 2)
        ];

        $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($BusinessData);

        if ($BusinessStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->ProductModel->rollback();
            $this->error('更新用户余额失败');
        }

        // 消费记录
        $RecordData = [
            'total' => $total,
            'busid' => $busid,
            'content' => "您的订单{$OrderData['code']}消费了{$total}元",
        ];

        $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);

        if ($RecordStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->ProductModel->rollback();
            $this->BusinessModel->rollback();
            $this->error($this->RecordModel->getError());
        }

        if ($OrderStatus === FALSE || $OrderProductStatus === FALSE || $ProductStatus === FALSE || $BusinessStatus === FALSE || $RecordStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->ProductModel->rollback();
            $this->BusinessModel->rollback();
            $this->RecordModel->rollback();
            $this->CartModel->rollback();
            $this->error('下单失败');
        } else {
            $this->OrderModel->commit();
            $this->OrderProductModel->commit();
            $this->ProductModel->commit();
            $this->BusinessModel->commit();
            $this->RecordModel->commit();
            $this->CartModel->commit();
            $this->success('下单成功');
        }
    }
}
